package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <b><code>EmployeeController</code></b>
 * <p/>
 * 员工信息controller
 * <p/>
 * <b>Creation Time:</b> 16/06/2024 20:46.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 员工登录
     * @param request request域
     * @param employee 用户名和密码
     * @return 用户信息
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request,  @RequestBody Employee employee) {
        Employee emp = employeeService.login(employee);
        if (emp == null) {
            return R.error("账号或密码错误");
        } else if (emp.getStatus() != 1) {
            return R.error("账号已禁用");
        }
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 用户退出
     * @param request request域
     * @return 提示
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增用户
     * @param request 请求域
     * @param employee 用户信息
     * @return 是否添加成功
     */
    @PostMapping
    public R<String> addEmployee(HttpServletRequest request, @RequestBody Employee employee) {
        return employeeService.addEmployee(employee);
    }

    /**
     * 用户分页查询
     * @param page 当前页
     * @param pageSize 每页显示条数
     * @param name 用户名
     * @return 查询的分页结果
     */
    @GetMapping("/page")
    public R<Page<Employee>> queryEmployee(@RequestParam(name = "page") int page,
                                 @RequestParam(name = "pageSize") int pageSize,
                                 @RequestParam(name = "name", required = false, defaultValue = "") String name) {
        return employeeService.queryEmployee(page, pageSize, name);
    }

    /**
     * 更新 用户
     * @param request 请求域
     * @param employee 请求参数
     * @return 是否成功
     */
    @PutMapping
    public R<String> updateEmployee(HttpServletRequest request, @RequestBody Employee employee) {
        return employeeService.updateEmployee(employee);
    }

    /**
     * 根据用户id查询用户信息
     * @param id 用户id
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public R<Employee> queryEmployeeById(@PathVariable("id") Long id) {
        return employeeService.queryEmployeeById(id);
    }


}
